package net.chowda.castcluster.action;

import net.chowda.castcluster.PlayList;
import net.chowda.castcluster.util.LogUtil;
import net.chowda.castcluster.playlist.PlayListManager;
import net.chowda.castcluster.util.RSSFeedAggregator;
import net.sourceforge.stripes.action.*;

import java.util.List;

import org.apache.log4j.Logger;

/**
 * User: dbachelder
 */
public class PlayListAction extends BaseAction {
    private static final Logger LOG = LogUtil.getLogger(PlayListAction.class);

    String playListId = null;
    String videoId = null;

    @DefaultHandler
    public Resolution doLists() throws Exception {
        List<PlayList> lists = PlayListManager.getAllPlayLists();
        context.getRequest().setAttribute("playLists", lists);
        //return new ForwardResolution("view/link_decider.jsp");
        return new ForwardResolution("view/playlist_list.jsp");
    }

    /**
     * @return his returns the actual feed consumed by iTunes (or whatever)
     * @throws Exception - die a horrible death
     */
    @HandlesEvent("feed")
    public Resolution feed() throws Exception {
        try {
            PlayList list = PlayListManager.getPlayList(playListId);
            if(list == null) throw new IllegalArgumentException("you requested an invalid feed id: " + playListId);
            String cast = RSSFeedAggregator.createPodcastFromVideos(list.getName(), list.getDescription(), PlayListManager.getVideosForList(list));
            StreamingResolution streamingResolution = new StreamingResolution("application/rss+xml", cast);
            streamingResolution.setCharacterEncoding("UTF-8");
            return streamingResolution.setFilename(playListId + ".xml");
        } catch (Exception e) {
            LOG.error("problem fetching feed.", e);
            throw new RuntimeException(e);
        }
    }

    @HandlesEvent("export")
    public Resolution export() throws Exception {
        String cast = PlayListManager.playListToXML(playListId);
        if(cast == null) throw new IllegalArgumentException("you requested an invalid feed id: " + playListId);
        StreamingResolution streamingResolution = new StreamingResolution("text/xml", cast);
        return streamingResolution.setFilename(playListId + ".xml");
    }

    public String getPlayListId() {
        return playListId;
    }

    public void setPlayListId(String playListId) {
        this.playListId = playListId;
    }

    public String getVideoId() {
        return videoId;
    }

    public void setVideoId(String videoId) {
        this.videoId = videoId;
    }
}
